<template>
  <div ref="chartDiv" :style="currStyle"></div>
</template>

<script setup>
import {ref, watch, onMounted, nextTick, markRaw} from 'vue';
import * as echarts from "echarts";
import visual from "@/visual/js/visual";
import * as chart from "@/visual/js/echarts";
import JSON5 from 'json5';
import { parseColors } from "@/utils/color";
import api from "@/http/api";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const chartDiv = ref();
const currChart = ref(null);
const currStyle = ref();

const init = async() => {
  if (currNode.value.compData.dataSourceType === '') {
    currNode.value.compData.dataSourceType = '静态数据';
  }
  const compStyle = props.compStyle || {};
  let style = '';
  style += visual.parseTpl('width: {value};', compStyle['width']);
  style += visual.parseTpl('height: {value};', compStyle['height']);
  currStyle.value = style;

  let defaultOption = {};
  try {
    defaultOption = JSON5.parse(compStyle['jsonOption'] || '{}');
  } catch (e) {
    console.log("jsonOption解释出错", e)
  }
  const dataList = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);

  const mapIds = (compStyle['geo.mapId'] || '156').split(',');
  const mapId = mapIds[mapIds.length - 1];

  const seriesData = [];
  (compStyle.seriesList || []).forEach(item => {
    seriesData.push({
      type: item.type,
      geoIndex: 0,
      coordinateSystem: item.type !== 'map' ? 'geo' : null,
      data: dataList[0]?.[item.prop]
    });
  });

  const option = {
    geo: parseGeo(compStyle, mapId),
    visualMap: parseVisualMap(compStyle),
    animation: compStyle['animation'] || false,
    color: parseColors(compStyle['colorScheme']),
    title: chart.parseTitle(compStyle),
    tooltip: chart.parseTooltip(compStyle),
    series: seriesData,
    toolbox: chart.parseToolbox(compStyle)
  };

  await nextTick(async() => {
    try {
      if (currChart.value) {
        echarts.dispose(chartDiv.value);
      }

      const json = await api.get(`/assets/map/${mapId}.json`, false);
      echarts.registerMap(mapId, json.data);
      currChart.value = markRaw(echarts.init(chartDiv.value));
      currChart.value.setOption(Object.assign({}, option, defaultOption));
    } catch (e) {
      console.log(e);
    }
  });
  await nextTick(() => currChart.value.resize());
};

const parseGeo = (compStyle, mapId) => {
  const result = { map: mapId, roam: true };

  result['label'] = {
    show: !!compStyle['geo.label'],
    position: compStyle['geo.label.position'] || 'inside',
    distance: compStyle['geo.label.distance'] || 5,
    formatter: compStyle['geo.label.formatter'] || '',
    color: compStyle['geo.label.color'] || '#fff',
    fontSize: compStyle['geo.label.fontSize'] || 12,
  };

  result['itemStyle'] = {
    areaColor: compStyle['geo.itemStyle.areaColor'] || '#eee',
    color: compStyle['geo.itemStyle.color'] || null,
    borderColor: compStyle['geo.itemStyle.borderColor'] || '#000',
    borderWidth: compStyle['geo.itemStyle.borderWidth'] || 0,
    borderType: compStyle['geo.itemStyle.borderType'] || 'solid',
  }

  return result;
};

const parseVisualMap = (compStyle) => {
  const resultList = [];

  (compStyle['visualMapList'] || []).forEach(item => {
    const result = {};
    result['show'] = !!item['show'];
    result['seriesIndex'] = item['seriesIndex'] || 0;
    result['calculable'] = true;
    result['type'] = item['type'] || 'continuous';
    result['min'] = item['min'] || null;
    result['max'] = item['max'] || null;
    result['orient'] = item['orient'] || 'horizontal';
    result['text'] = item['text'] ? item['text'].split(',') : null;
    result['dimension'] = item['dimension'] || null;

    result['inRange'] = {};
    if (item['inRange.symbol']) {
      result['inRange'].symbol = item['inRange.symbol'] || 'pin';
    }
    if (item['inRange.symbolSize']) {
      result['inRange'].symbolSize = item['inRange.symbolSize'].split(',');
    }
    if (item['inRange.color']) {
      result['inRange'].color = item['inRange.color'].split(',');
    }

    resultList.push(result);
  });

  return resultList;
};

watch(() => props.compStyle, () => {
  init();
}, { deep: true });

watch(() => props.compData?.refresh, () => {
  init();
});

onMounted(() => {
  init();
});
</script>